import { Context } from 'koa';
import { AppDataSource } from '@/config/database';
import { Product } from '@/entities/basis/product.entity';
import { ICreateProductDto, IUpdateProductDto, IProductQueryDto } from '@/entities/basis/product.entity/interfaces';

// 扩展 Context 类型以包含 request.body
interface ExtendedContext extends Context {
    request: Context['request'] & {
        body?: any;
    };
}

const productRepository = AppDataSource.getRepository(Product);

/**
 * 产品管理控制器
 */
export class ProductController {

    /**
     * 创建产品
     */
    static async create(ctx: ExtendedContext) {
        try {
            const productData: ICreateProductDto = ctx.request.body;
            
            // 检查产品编号是否已存在
            const existingProduct = await productRepository.findOne({
                where: { code: productData.code }
            });
            
            if (existingProduct) {
                ctx.status = 400;
                ctx.body = {
                    success: false,
                    message: '产品编号已存在'
                };
                return;
            }

            // 创建新产品
            const newProduct = productRepository.create({
                ...productData,
                createdBy: ctx.state.user?.id || 'system',
                status: productData.status || 'active',
                unit: productData.unit || '瓶',
                stockQuantity: productData.stockQuantity || 0,
                warningQuantity: productData.warningQuantity || 10,
                isRecommended: productData.isRecommended || false
            });

            const savedProduct = await productRepository.save(newProduct);

            ctx.status = 201;
            ctx.body = {
                success: true,
                message: '产品创建成功',
                data: savedProduct
            };
        } catch (error) {
            console.error('创建产品失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '创建产品失败',
                error: error.message
            };
        }
    }

    /**
     * 获取产品列表
     */
    static async getList(ctx: Context) {
        try {
            const query: IProductQueryDto = ctx.query;
            const page = parseInt(query.page as string) || 1;
            const pageSize = parseInt(query.pageSize as string) || 10;
            const skip = (page - 1) * pageSize;

            // 构建查询条件，使用QueryBuilder处理复杂查询
            const queryBuilder = productRepository.createQueryBuilder('product');

            // 处理keyword参数，同时搜索产品名称和编号
            if (query.keyword) {
                queryBuilder.andWhere(
                    '(product.name LIKE :keyword OR product.code LIKE :keyword)',
                    { keyword: `%${query.keyword}%` }
                );
            }

            if (query.name) {
                queryBuilder.andWhere('product.name LIKE :name', { name: `%${query.name}%` });
            }
            
            if (query.category) {
                queryBuilder.andWhere('product.category = :category', { category: query.category });
            }
            
            if (query.brand) {
                queryBuilder.andWhere('product.brand = :brand', { brand: query.brand });
            }
            
            if (query.status) {
                queryBuilder.andWhere('product.status = :status', { status: query.status });
            }
            
            if (query.isRecommended !== undefined) {
                const isRecommendedValue = Array.isArray(query.isRecommended) 
                    ? query.isRecommended[0] 
                    : query.isRecommended;
                queryBuilder.andWhere('product.isRecommended = :isRecommended', { 
                    isRecommended: isRecommendedValue === 'true' 
                });
            }

            // 构建价格范围查询
            if (query.minPrice !== undefined && query.maxPrice !== undefined) {
                queryBuilder.andWhere('product.retailPrice BETWEEN :minPrice AND :maxPrice', {
                    minPrice: Number(query.minPrice),
                    maxPrice: Number(query.maxPrice)
                });
            } else if (query.minPrice !== undefined) {
                queryBuilder.andWhere('product.retailPrice > :minPrice', { minPrice: Number(query.minPrice) });
            } else if (query.maxPrice !== undefined) {
                queryBuilder.andWhere('product.retailPrice <= :maxPrice', { maxPrice: Number(query.maxPrice) });
            }

            // 库存查询
            if (query.inStock !== undefined) {
                const inStockValue = Array.isArray(query.inStock) 
                    ? query.inStock[0] 
                    : query.inStock;
                if (inStockValue === 'true') {
                    queryBuilder.andWhere('product.stockQuantity > 0');
                } else if (inStockValue === 'false') {
                    queryBuilder.andWhere('product.stockQuantity <= 0');
                }
            }

            // 构建排序条件，让上架商品优先显示，然后按更新时间倒序
            queryBuilder
                .skip(skip)
                .take(pageSize)
                .orderBy(
                    `CASE 
                        WHEN product.status = 'active' THEN 1 
                        WHEN product.status = 'draft' THEN 2 
                        ELSE 3 
                    END`, 'ASC'
                )
                .addOrderBy('product.updatedAt', 'DESC');

            const [products, total] = await queryBuilder.getManyAndCount();

            ctx.body = {
                success: true,
                message: '获取产品列表成功',
                data: {
                    items: products,
                    pagination: {
                        page,
                        pageSize,
                        total,
                        totalPages: Math.ceil(total / pageSize)
                    }
                }
            };
        } catch (error) {
            console.error('获取产品列表失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取产品列表失败',
                error: error.message
            };
        }
    }

    /**
     * 根据ID获取产品详情
     */
    static async getById(ctx: Context) {
        try {
            const { id } = ctx.params;
            
            const product = await productRepository.findOne({
                where: { id }
            });

            if (!product) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: '产品不存在'
                };
                return;
            }

            ctx.status = 200;
            ctx.body = {
                ...product,
                retailPrice: Number(product.retailPrice),
                memberPrice: Number(product.memberPrice),
                costPrice: Number(product.costPrice),
            };
        } catch (error) {
            console.error('获取产品详情失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取产品详情失败',
                error: error.message
            };
        }
    }

    /**
     * 更新产品
     */
    static async update(ctx: ExtendedContext) {
        try {
            const { id } = ctx.params;
            const updateData: IUpdateProductDto = ctx.request.body;

            const product = await productRepository.findOne({
                where: { id }
            });

            if (!product) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: '产品不存在'
                };
                return;
            }

            // 更新产品信息
            Object.assign(product, updateData, {
                updatedBy: ctx.state.user?.id || 'system'
            });

            const updatedProduct = await productRepository.save(product);

            ctx.body = {
                success: true,
                message: '产品更新成功',
                data: updatedProduct
            };
        } catch (error) {
            console.error('更新产品失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '更新产品失败',
                error: error.message
            };
        }
    }

    /**
     * 删除产品
     */
    static async delete(ctx: Context) {
        try {
            const { id } = ctx.params;
            
            const product = await productRepository.findOne({
                where: { id }
            });

            if (!product) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: '产品不存在'
                };
                return;
            }

            // 软删除产品
            await productRepository.softDelete(id);

            ctx.body = {
                success: true,
                message: '产品删除成功'
            };
        } catch (error) {
            console.error('删除产品失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '删除产品失败',
                error: error.message
            };
        }
    }

    /**
     * 批量更新产品状态
     */
    static async batchUpdateStatus(ctx: ExtendedContext) {
        try {
            const { ids, status } = ctx.request.body;
            
            if (!Array.isArray(ids) || ids.length === 0) {
                ctx.status = 400;
                ctx.body = {
                    success: false,
                    message: '请选择要更新的产品'
                };
                return;
            }

            await productRepository.update(ids, {
                status,
                updatedBy: ctx.state.user?.id || 'system'
            });

            ctx.body = {
                success: true,
                message: '批量更新产品状态成功'
            };
        } catch (error) {
            console.error('批量更新产品状态失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '批量更新产品状态失败',
                error: error.message
            };
        }
    }

    /**
     * 获取产品分类列表
     */
    static async getCategories(ctx: Context) {
        try {
            const categories = await productRepository
                .createQueryBuilder('product')
                .select('DISTINCT product.category', 'category')
                .where('product.category IS NOT NULL')
                .andWhere('product.category != ""')
                .getRawMany();

            const categoryList = categories.map(item => item.category);

            ctx.body = {
                success: true,
                message: '获取产品分类成功',
                data: categoryList
            };
        } catch (error) {
            console.error('获取产品分类失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取产品分类失败',
                error: error.message
            };
        }
    }

    /**
     * 获取产品品牌列表
     */
    static async getBrands(ctx: Context) {
        try {
            const brands = await productRepository
                .createQueryBuilder('product')
                .select('DISTINCT product.brand', 'brand')
                .where('product.brand IS NOT NULL')
                .andWhere('product.brand != ""')
                .getRawMany();

            const brandList = brands.map(item => item.brand);

            ctx.body = {
                success: true,
                message: '获取产品品牌成功',
                data: brandList
            };
        } catch (error) {
            console.error('获取产品品牌失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取产品品牌失败',
                error: error.message
            };
        }
    }

    /**
     * 库存预警检查
     */
    static async checkStockWarning(ctx: Context) {
        try {
            const warningProducts = await productRepository
                .createQueryBuilder('product')
                .where('product.stockQuantity <= product.warningQuantity')
                .andWhere('product.status = :status', { status: 'active' })
                .getMany();

            ctx.body = {
                success: true,
                message: '获取库存预警产品成功',
                data: warningProducts
            };
        } catch (error) {
            console.error('获取库存预警产品失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取库存预警产品失败',
                error: error.message
            };
        }
    }
} 